﻿using System;
using System.Collections.Generic;
using AutoMapper;
using Budget.Core.Data;
using Budget.Core.DomainModel;
using Budget.Core.Extensions;
using Budget.Core.Specifications;
using Budget.Wcf.Core.Dto;
using Budget.Wcf.Core.Interfaces;
using Castle.Core.Logging;

namespace Budget.Wcf.Services
{
    public class IncomeService : BaseService, IIncomeService
    {
        private readonly IRepository<IncomeType> incomeTypeRepo;
        private readonly IRepository<IncomeOrder> incomeOrderRepo;
        private readonly IRepository<Balance> balanceRepo;

        public IncomeService(ILogger logger, IRepository<IncomeType> incomeTypeRepo, IRepository<IncomeOrder> incomeOrderRepo, IRepository<Balance> balanceRepo)
            : base(logger)
        {
            this.incomeTypeRepo = incomeTypeRepo;
            this.incomeOrderRepo = incomeOrderRepo;
            this.balanceRepo = balanceRepo;
        }

        public IList<IncomeTypeData> GetAllIncomeTypes()
        {
            try
            {
                var dbIncomeTypes = incomeTypeRepo.Find.All();
                var dataIncomeTypes = Mapper.Map<IList<IncomeType>, IList<IncomeTypeData>>(dbIncomeTypes);
                return dataIncomeTypes;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Details());
                return null;
            }
        }

        public IList<IncomeOrderData> GetAllIncomeOrders()
        {
            try
            {
                var dbOrders = incomeOrderRepo.Find.All();
                var dataOrders = Mapper.Map<IList<IncomeOrder>, IList<IncomeOrderData>>(dbOrders);
                return dataOrders;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Details);
                return null;
            }
        }

        public void AddIncomeOrder(IncomeOrderData incomeOrder)
        {
            try
            {
                var lastBalance = balanceRepo.Find.One(BalanceSpecifications.Latest());
                var type = Mapper.Map<IncomeType>(incomeOrder.IncomeType);
                var dbOrder = new IncomeOrder(type, lastBalance) { CreationDate = incomeOrder.CreationDate, Amount = incomeOrder.Amount };
                incomeOrderRepo.SaveOrUpdate(dbOrder);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Details());
            }
        }
    }
}